//
//  XMLParserViewController.m
//  Archiver
//
//  Created by LiJonius on 16/3/24.
//  Copyright © 2016年 LiJonius. All rights reserved.
//

#import "XMLParserViewController.h"
#import "Book.h"
@interface XMLParserViewController ()
@property (nonatomic, copy)NSString *currentString;
@property (nonatomic, strong)Book *currentBook;
@property (nonatomic, strong)NSMutableArray *books;
@end
//  遵守 协议   NSXMLParserDelegate
@implementation XMLParserViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.books = [NSMutableArray array];
    //创建并 初始化数据源

    NSString* path=[[NSBundle mainBundle]pathForResource:@"books" ofType:@"xml"];
    
    NSData *xmlData = [NSData dataWithContentsOfFile:path];
    //创建并初始化 XML数据解析对象
    NSXMLParser *parser = [[NSXMLParser alloc]initWithData:xmlData];
    //设置代理
    parser.delegate = self;
    //解析
    [parser parse];
    
    for (Book *book in self.books) {
        NSLog(@"%@",book);
    }
    
    for (int i = 0 ; i<self.books.count; i++) {
        
        Book* book = self.books[i];
        UILabel * label = [[UILabel alloc]initWithFrame:CGRectMake(10 , 120 + i%3 * 20, 300, 15)];
        //已经重写了Book description 方法
        label.text = [NSString stringWithFormat:@"%@",book];
        [self.view addSubview:label];
    }
    
}
-(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict{
    // 第一步
    NSLog(@"didStartElement  %@",elementName);
    if ([elementName isEqualToString:@"book"]) {
        self.currentBook = [[Book alloc]init];
        [self.books addObject:self.currentBook];
    }
}
-(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string{
     NSLog(@"foundCharacters===%@",string);
    // 第二步骤 除了元素符号 以外的信息
    self.currentString = string;
    
}

-(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName{
    // 第三步骤
     NSLog(@"didEndElement %@",elementName);
    if ([elementName isEqualToString:@"name"]) {
        self.currentBook.name = self.currentString;
    }else if ([elementName isEqualToString:@"author"]) {
        self.currentBook.author = self.currentString;
    }else if ([elementName isEqualToString:@"page"]) {
        self.currentBook.page = [self.currentString intValue];
    }else if ([elementName isEqualToString:@"price"]) {
        self.currentBook.price = [self.currentString intValue];
    }
    
    
    
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
